package socket.example4;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author lhn
 * @date 2024-04-25 15:40
 * 文件上传的服务端
 */

public class SocketTCP04FileUploadServer {
    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(9999);
        System.out.println("服务端-端口9999等待连接...");
        Socket socket = serverSocket.accept();

        //读取客户端发送的数据
        BufferedInputStream bufferedInputStream = new BufferedInputStream(socket.getInputStream());
        byte[] bytes = StreamUtils.streamToByteArray(bufferedInputStream);
        //获取当前的工作目录
        String serverPath = System.setProperty("user.dir", "path/to/directory") + "\\0.jpeg";
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(new FileOutputStream(serverPath));
        bufferedOutputStream.write(bytes);
        bufferedOutputStream.close();

        //向客户端发送 收到图片的消息然后退出
        BufferedWriter bufferedWriter = new BufferedWriter(
                new OutputStreamWriter(socket.getOutputStream())
        );
        bufferedWriter.write("收到图片");
        bufferedWriter.newLine();
        bufferedWriter.flush();
        socket.shutdownOutput();

        bufferedWriter.close();
        bufferedInputStream.close();
        socket.close();
        serverSocket.close();


    }
}
